package com.github.shuaidd.rest.editor;

import lombok.AllArgsConstructor;
import org.activiti.app.constant.GroupTypes;
import org.activiti.app.model.common.ResultListDataRepresentation;
import org.activiti.engine.IdentityService;
import org.activiti.engine.identity.Group;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("app")
@AllArgsConstructor(onConstructor_ = {@Autowired})
public class EditorGroupsResource {

    private final IdentityService identityService;

    @RequestMapping(value = "/rest/editor-groups", method = RequestMethod.GET)
    public ResultListDataRepresentation getGroups(@RequestParam(required = false, value = "filter") String filter) {
        String groupNameFilter = filter;
        if (StringUtils.isEmpty(groupNameFilter)) {
            groupNameFilter = "%";
        } else {
            groupNameFilter = "%" + groupNameFilter + "%";
        }
        List<Group> matchingGroups = identityService.createGroupQuery()
                .groupNameLike(groupNameFilter)
                .groupType(GroupTypes.TYPE_ASSIGNMENT)
                .list();

        // TODO: get total result count instead of page-count, in case the matching
        // list's size is equal to the page size
        return new ResultListDataRepresentation(matchingGroups);
    }
}
